import { _decorator, CCInteger, Component, director, instantiate, Node, Prefab } from 'cc';
import GameController from '../script/GameController';
import { EventEnum, MJStyleEnum } from '../script/Enum';
import { MJ } from './MJ';
const { ccclass, property } = _decorator;

@ccclass('Line')
export class Line extends Component {

    @property(CCInteger)
    private index: number = 0;

    @property(Prefab)
    mjLie: Prefab = null;

    private list = [];

    protected onLoad(): void {
        director.on(EventEnum.EVENT_SHUFFLE, this.onShuffle, this);
        director.on(EventEnum.EVENT_DECKPOP, this.onPop, this);

        this.onShuffle();
    }

    start() {

    }

    update(deltaTime: number) {

    }

    public get Index() {
        return this.index;
    }

    public onShuffle() {
        let deck = GameController.getInstance().getDeck(this.index);
        let list: any[] = deck.splice(0, Math.min(deck.length, 9));
        console.log(list);
        for (let i = list.length - 1; i >= 0; i--) {
            let mj = instantiate(this.mjLie);
            mj.getComponent(MJ).Style = MJStyleEnum.STYLE_LIE;
            mj.getComponent(MJ).MJValue = list[i];
            mj.getComponent(MJ).Line = this.list;
            mj.getComponent(MJ).setIndex(this.index);
            this.node.addChild(mj);
            this.list.push(mj);
            for (let i = 0; i < this.list.length; i++) {
                this.list[i].setSiblingIndex(i);
            }
        }
    }

    public onPop(deck) {
        if (deck != this.index) {
            return;
        }
        this.node.removeChild(this.list.pop());

        let mjValue = GameController.getInstance().getMjInDeck(deck, this.list.length);
        if (mjValue == null) {
            return;
        }

        let mj = instantiate(this.mjLie);
        mj.getComponent(MJ).Style = MJStyleEnum.STYLE_LIE;
        mj.getComponent(MJ).MJValue = mjValue;
        mj.getComponent(MJ).Line = this.list;
        console.log(this.list);
        mj.getComponent(MJ).setIndex(this.index);
        this.node.addChild(mj);
        this.list.unshift(mj);
        for (let i = 0; i < this.list.length; i++) {
            this.list[i].setSiblingIndex(i);
        }
    }
}

